package com.feihong.txgw.ui.activity.user;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.adapter.base.BaseQuickAdapter;
import com.amap.api.services.core.AMapException;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.LogUtils;
import com.feihong.txgw.R;
import com.feihong.txgw.adapter.delivery.DeliverySearchPoiDataReAdapter;
import com.feihong.txgw.message.DelvieryAdrSelectMessage;
import com.feihong.txgw.message.LoginMessage;
import com.feihong.txgw.model.bean.deliveryAdr.AdressSelectMapPoiInfoEntity;
import com.feihong.txgw.ui.activity.base.BaseActivity;
import com.feihong.txgw.ui.activity.kaika.KaikaManager;
import com.feihong.txgw.utils.ToastUtils;
import com.feihong.txgw.utils.UserLoginInfo;
import com.megvii.livenesslib.util.ConUtil;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * @author wangziheng
 * @name txgw_app
 * @class name：com.feihong.txgw.ui.activity.user
 * @class describe:
 * @time 2018/3/8 12:51
 * @change
 * @chang time
 * @class describe
 */
public class AdrSearchActivity extends BaseActivity implements
        PoiSearch.OnPoiSearchListener,
        View.OnClickListener,
        BaseQuickAdapter.RequestLoadMoreListener{
    @BindView(R.id.search_adr_recyclerver_layout) RecyclerView mRecyclerView;
    @BindView(R.id.et_search) EditText mSearchEditText;
    @BindView(R.id.AdrSearchNearPoiRefershLayout) SwipeRefreshLayout mRefreshLayout;
    @BindView(R.id.activity_adr_search_status_layout) View mStatusLayout;
    private String mKeyWord;
    /**
     * 当前页面，从0开始计数
     */
    private int mCurrentPage = 1;
    private String mCityCode;
    private PoiSearch mPoiSearch;
    private LatLonPoint mLatLonPoint;
    private LinearLayoutManager mLinearLayoutManager;
    private DeliverySearchPoiDataReAdapter mReAdapter;
    public static final String MAP_POI_SEARCH_INFO_KEY = "MAP_POI_SEARCH_INFO_KEY";
    /**
     * poi返回的结果
     */
    private PoiResult poiResult;
    /**
     * poi数据
     */

    private RelativeLayout mBackLayout;

    private boolean isHasData = false;
    @Override
    public void setTheme() {

    }

    @Override
    public int setLayoutID() {
        return R.layout.activity_search_adr_layout;
    }

    private PoiSearch.Query query;

    @Override
    public void initView(Bundle savedInstanceState) {
        setSpecificTitleLayout(mStatusLayout);
        KaikaManager.getmKaikaManager().addStack(this);
        mSearchEditText.setFocusable(true);
        mSearchEditText.setHint(getResources().getString(R.string.delivery_adr_map_poi_search_content));
        Intent intent = getIntent();
        Bundle bundle = intent.getExtras();
        AdressSelectMapPoiInfoEntity poiInfoEntity = (AdressSelectMapPoiInfoEntity) bundle.get(MAP_POI_SEARCH_INFO_KEY);
        if (TextUtils.isEmpty(poiInfoEntity.getCity())) {
            mCityCode = UserLoginInfo.getUserCityInfo().getCityCode();
            double lat = TextUtils.isEmpty(UserLoginInfo.getUserCityInfo().getLatitude()) ? 0 : Double.valueOf(UserLoginInfo.getUserCityInfo().getLatitude());
            double lnt = TextUtils.isEmpty(UserLoginInfo.getUserCityInfo().getLongitude()) ? 0 : Double.valueOf(UserLoginInfo.getUserCityInfo().getLongitude());
            mLatLonPoint = new LatLonPoint(lat, lnt);
        } else {
            double lat;
            double lnt;
            if(TextUtils.isEmpty(poiInfoEntity.getLatitude())){
                lat = TextUtils.isEmpty(UserLoginInfo.getUserCityInfo().getLatitude()) ? 0 : Double.valueOf(UserLoginInfo.getUserCityInfo().getLatitude());
                lnt = TextUtils.isEmpty(UserLoginInfo.getUserCityInfo().getLongitude()) ? 0 : Double.valueOf(UserLoginInfo.getUserCityInfo().getLongitude());
            }else {

                lat = TextUtils.isEmpty(poiInfoEntity.getLatitude()) ? 0 : Double.valueOf(poiInfoEntity.getLatitude());
                lnt = TextUtils.isEmpty(poiInfoEntity.getLongitude()) ? 0 : Double.valueOf(poiInfoEntity.getLongitude());
            }
            mCityCode = poiInfoEntity.getCityCode();
            mLatLonPoint = new LatLonPoint(lat, lnt);
        }
        mKeyWord = mSearchEditText.getText().toString().trim();
//        query = new PoiSearch.Query(mKeyWord, "", mCityCode);
//        //keyWord表示搜索字符串，
//        //第二个参数表示POI搜索类型，二者选填其一，选用POI搜索类型时建议填写类型代码，码表可以参考下方（而非文字）
//        //cityCode表示POI搜索区域，可以是城市编码也可以是城市名称，也可以传空字符串，空字符串代表全国在全国范围内进行搜索
//        // 设置每页最多返回多少条poiitem
//        query.setPageSize(10);
//        //设置查询页码
//        query.setPageNum(mCurrentPage);
        mLinearLayoutManager = new LinearLayoutManager(this);
        mRecyclerView.setLayoutManager(mLinearLayoutManager);
        mRefreshLayout.setRefreshing(true);
        mRefreshLayout.setColorSchemeColors(Color.rgb(223, 47, 47));
        doSearchQuery();
        mBackLayout = (RelativeLayout) findViewById(R.id.back);
        mBackLayout.setOnClickListener(this);
        mSearchEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                mCurrentPage = 1;
                isHasData = false;
                doSearchQuery();
            }
        });
        mSearchEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                mCurrentPage = 1;
                isHasData = false;
                doSearchQuery();
                KeyboardUtils.hideSoftInput(AdrSearchActivity.this);
                return false;
            }
        });
        mRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                isHasData = false;
                mCurrentPage = 1;
                doSearchQuery();
            }
        });
    }

    @Override
    public void bindData() {
        mReAdapter = new DeliverySearchPoiDataReAdapter(R.layout.delivery_search_poi_item_layout);
        mReAdapter.setOnLoadMoreListener(this,mRecyclerView);
        mRecyclerView.setAdapter(mReAdapter);
        mReAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                DelvieryAdrSelectMessage delvieryAdrSelectMessage = new DelvieryAdrSelectMessage();
                PoiItem poiItem = (PoiItem) adapter.getItem(position);
                delvieryAdrSelectMessage.setPoiItem(poiItem);
                EventBus.getDefault().post(delvieryAdrSelectMessage);
                ConUtil.isGoneKeyBoard(AdrSearchActivity.this);
                KaikaManager.getmKaikaManager().clearAll();
            }
        });
    }

    @Override
    public void onUserLogin(LoginMessage loginMessage) {

    }

    /**
     * 开始进行poi搜索
     */
    protected void doSearchQuery() {
        mKeyWord = mSearchEditText.getText().toString().trim();
        // 第一个参数表示搜索字符串，第二个参数表示poi搜索类型，第三个参数表示poi搜索区域（空字符串代表全国）
        query = new PoiSearch.Query(mKeyWord, MapAddressActivity.MAP_POI_TYPE, mCityCode);
        // 设置每页最多返回多少条poiitem
        query.setPageSize(20);
        // 设置查第一页
        query.setPageNum(mCurrentPage);
        if (mLatLonPoint != null) {
            mPoiSearch = new PoiSearch(this, query);
            mPoiSearch.setOnPoiSearchListener(this);
            mPoiSearch.setBound(new PoiSearch.SearchBound(mLatLonPoint, 5000, true));
            // 设置搜索区域为以lp点为圆心，其周围5000米范围
            mPoiSearch.searchPOIAsyn();// 异步搜索
        }
    }


    @Override
    public void onPoiSearched(PoiResult result, int rcode) {
        if (activityIsDestory()) {
            return;
        }
        finishRefreshing();
        try {
            if (rcode == AMapException.CODE_AMAP_SUCCESS) {
                //搜索poi的结果
                if (result != null && result.getQuery() != null) {
                    // 是否是同一条
                    if (result.getQuery().equals(query)) {
                        poiResult = result;
                        // 取得第一页的poiitem数据，页数从数字0开始
                        List<PoiItem> mPoiItems = poiResult.getPois();
//                    List<SuggestionCity> suggestionCities = poiResult
//                            .getSearchSuggestionCitys();// 当搜索不到poiitem数据时，会返回含有搜索关键字的城市信息
//                    if (poiItems != null && poiItems.size() > 0) {
//                        StringBuilder stringBuilder = new StringBuilder();
//                        for(PoiItem poiItem : poiItems){
//                            stringBuilder.append("toString:"+poiItem.toString()+"  getDirection:"+poiItem.getDirection()+" getCityName:"+poiItem.getCityName()+" getAdName:"
//                            +poiItem.getAdName()+" getBusinessArea:"+poiItem.getBusinessArea()+"\n");
//                        }
                        if (mPoiItems != null && mPoiItems.size() != 0) {
                            if(mCurrentPage < 2){
                                mReAdapter.setNewData(mPoiItems);
                            }else {
                                mReAdapter.addData(mPoiItems);
                            }
                            isHasData = true;
                            mCurrentPage++;
                            mReAdapter.loadMoreComplete();
                        } else {
                            if (mPoiItems.size() == 0) {
                                ToastUtils.getInstance().showShortToast(
                                        "没有搜索到相关数据");
                            }
                            mReAdapter.loadMoreEnd(true);
                        }

//                    } else if (suggestionCities != null
//                            && suggestionCities.size() > 0) {
//                    } else {
//                        ToastUtils.getInstance().showShortToast(
//                                "没有搜索到相关数据");
//                    }
                    }
                } else {
                    if (!isHasData) {
                        ToastUtils.getInstance().showShortToast(
                                "没有搜索到相关数据");
                    }
                    mReAdapter.loadMoreEnd(true);
                }
            } else {if (!isHasData) {
                ToastUtils.getInstance().showShortToast(
                        "没有搜索到相关数据");
            }
                mReAdapter.loadMoreEnd(true);
                LogUtils.i("高德poi搜索错误：" + rcode);
            }
        } catch (Exception e) {if (!isHasData) {
            ToastUtils.getInstance().showShortToast(
                    "没有搜索到相关数据");
        }
            mReAdapter.loadMoreEnd(true);
        }
    }

    @Override
    public void onPoiItemSearched(PoiItem poiItem, int i) {

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back:
                ConUtil.isGoneKeyBoard(AdrSearchActivity.this);
                finish();
                break;
            default:
                break;
        }
    }

    @Override
    public void onBackPressedSupport() {
        super.onBackPressedSupport();
        ConUtil.isGoneKeyBoard(AdrSearchActivity.this);
    }

    @Override
    public void onLoadMoreRequested() {
        doSearchQuery();
    }

    private void finishRefreshing(){
        if(mRefreshLayout.isRefreshing()){
            mRefreshLayout.setRefreshing(false);
        }
    }
}
